package com.example.test.chapter14;

import com.example.test.R;

import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.SimpleCursorAdapter;

public class MyNotepadA extends ListActivity {
	private int mNoteNumber = 1;
	private NotesDbAdapter notesDbAdapter;
	private static final int INSERT_ID = Menu.FIRST;
	private Cursor cursor;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.notepad_list);
		notesDbAdapter = new NotesDbAdapter(this);
		notesDbAdapter.open();
		fillData();
		Button btn = (Button) findViewById(R.id.backpage);
		btn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(getApplicationContext(),
						MainChapter14.class);
				startActivity(intent);
				if (notesDbAdapter != null) {
					notesDbAdapter.close();
				}
				finish();
			}
		});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		boolean result = super.onCreateOptionsMenu(menu);
		menu.add(0, INSERT_ID, 0, R.string.menu_insert);
		return result;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case INSERT_ID:
			createNote();
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	private void createNote() {
		String noteName = "Note " + mNoteNumber++;
		notesDbAdapter.createNote(noteName, "");
		fillData();
	}

	private void fillData() {
		cursor = notesDbAdapter.fechtAllNotes();
		startManagingCursor(cursor);
		String[] from = new String[] { NotesDbAdapter.KEY_TITLE };
		int[] to = new int[] { R.id.textNotesRow };
		SimpleCursorAdapter cursorAdapter = new SimpleCursorAdapter(this,
				R.layout.notes_row, cursor, from, to);
		setListAdapter(cursorAdapter);
	}

}
